<template>
  <view :style="pageStyle">
    <view class="bg-transparent height-p-100">
      <!--有数据-->
      <view class="height-p-100" v-if="$data.list.length > 0">
        <!--列表插槽-->
        <slot name="render"></slot>
        <!-- <slot></slot> -->
        <!--列表底部提示-->
        <view
          v-if="showBottomLoadText"
          class="padding-bottom padding-top-xxl text-center"
        >
          <!-- <u-loadmore bg-color="rgba(0, 0, 0, 0)" :is-dot="false" :font-size="30" :status="status" :load-text="bottomLoadText" /> -->
          <uni-load-more
            :icon-size="30"
            :status="$data.status"
            :content-text="bottomLoadText"
          ></uni-load-more>
        </view>
      </view>
      <!--无数据-->
      <view v-else>
        <view v-if="customEmpty">
          <slot name="empty"></slot>
        </view>
        <view v-else class="padding-top-xxl bg-transparent height-p-100">
          <!-- <u-empty v-if="isLoad" :width="400" :height="400" :text-size="30" mode="search" text="加载中">
					</u-empty>
					<u-empty v-else :mode="emptyMode" :width="400" :height="400" :text-size="30" :icon="emptyIcon" text="暂无数据"></u-empty> -->
          <wakin-data-empty
            :message="$data.isLoad ? '加载中' : '暂无数据'"
          ></wakin-data-empty>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { LoadEnum, _getKeyVal } from "./config";
import WakinDataEmpty from "../wakin-data-empty/wakin-data-empty.vue";
import { getCurrentInstance, reactive, watch } from "vue";
import BasicConfig from "@/utils/config";
const $vm = getCurrentInstance()?.appContext.config.globalProperties;
const $emit = defineEmits(["loadStatus", "loadData"]);
const $props = defineProps({
  pageNumKey: {
    type: String,
    default: "page",
  },
  pageSizeKey: {
    type: String,
    default: "limit",
  },
  /** 分页页码起始数 */
  pageStartNum: {
    type: Number,
    default: 1,
  },
  resDataKey: {
    type: Array,
    default: () => ["rows"],
  },
  resTotalKey: {
    type: Array,
    default: () => ["total"],
  },
  resCodeKey: {
    type: Array,
    default: () => ["code"],
  },
  customTotalFn: {
    type: Function,
    default: () => null,
  },
  pageStyle: {
    type: String,
    default: "",
  },
  height: {
    type: [Number, String],
    default: "100%",
  },
  // 是否显示加载中toast
  showLoadToast: {
    type: Boolean,
    default: false,
  },
  // 是否加载底部过场文字
  showBottomLoadText: {
    type: Boolean,
    default: true,
  },
  // 底部加载文字
  bottomLoadText: {
    type: Object,
    default: () => {
      return {
        contentdown: "轻轻上拉",
        contentrefresh: "努力加载中",
        contentnomore: "没有数据了",
      };
    },
  },
  // 默认空提示时使用的icon
  emptyMode: {
    type: String,
    default: "data",
  },
  // 默认空提示时使用的icon
  emptyIcon: {
    type: String,
    default: "", // require('./images/search.png')
  },
  // 是否使用自定义空提示
  customEmpty: {
    type: Boolean,
    default: false,
  },
  statusCode: {
    type: [Number, String],
    default: 200,
  },
});
const $data = reactive({
  list: [], // 列表数组
  // {contentdown: "上拉显示更多",contentrefresh: "正在加载...",contentnomore: "没有更多数据了"}
  status: "contentrefresh", // loading:加载中 loadmore:加载更多 nomore:没有更多了
  total: 0, // 数据总数
  isLoad: true, // 加载中
});

/**
 * @description 加载数据列表
 * @param {String} loadType 加载类型 => load:首次/重新加载,bottom:触底(上滑)加载
 * @param {Object} search 搜索条件
 * @param {Boolean} debounce 开启防抖
 * @param {Number} time 防抖时间
 * @param {Function} api 接口
 */
const loadDatas = async ({
  loadType = LoadEnum.load,
  search,
  debounce = false,
  time = 1000,
  api,
  apiConfig = {},
}) => {
  // 搜索防抖
  if (debounce) {
    uni.$u.debounce(
      async () => {
        await _loadDatas(loadType, search, api, apiConfig);
      },
      time,
      false
    );
  }
  // 加载
  else {
    _loadDatas(loadType, search, api, apiConfig);
  }
};
// 加载状态判断
const onLoadStatus = () => {
  if ($data.isLoad) {
    $data.status = "contentrefresh";
  } else {
    $data.status =
      $data.list.length < $data.total ? "contentdown" : "contentnomore";
  }
};
const _loadDatas = async (loadType, search, api, apiConfig) => {
  $data.isLoad = loadType === LoadEnum.load || $data.list.length < $data.total;
  switch (loadType) {
    case LoadEnum.load:
      search[$props.pageNumKey] = $props.pageStartNum;
      $data.list = [];
      try {
        await api(search, apiConfig).then((res) => {
          const code = _getKeyVal(res, $props.resCodeKey);
          if (code === $props.statusCode) {
            $data.total = Number(
              $props.customTotalFn(res, $data.total) ??
                _getKeyVal(res, $props.resTotalKey)
            );
            $data.list = _getKeyVal(res, $props.resDataKey);
          } else {
            // BasicConfig.toast(res.msg);
          }
          $emit("loadData", $data.list, $data.total, res);
        });
      } catch (err) {
        console.error("wakin-list-temp-error:", err);
      }
      $data.isLoad = false;
      break;
    case LoadEnum.bottom:
      if ($data.list.length < $data.total) {
        search[$props.pageNumKey] = ++search[$props.pageNumKey];
        try {
          await api(search, apiConfig).then((res) => {
            const code = _getKeyVal(res, $props.resCodeKey);
            let list = [];
            if (code === $props.statusCode) {
              $data.total = Number(
                $props.customTotalFn(res, $data.total) ??
                  _getKeyVal(res, $props.resTotalKey)
              );
              list = _getKeyVal(res, $props.resDataKey);
              $data.list = [...$data.list, ...list];
            } else {
              // BasicConfig.toast({
              //   msg: res.msg || res.message,
              // });
            }
            $emit("loadData", $data.list, $data.total, res);
          });
        } catch (err) {
          console.error("wakin-list-temp-error:", err);
        }
        $data.isLoad = false;
      }
      break;
    default:
      $data.isLoad = false;
      break;
  }
};

watch(
  () => $data.isLoad,
  (n, o) => {
    if (n) {
      if ($props.showLoadToast) BasicConfig.loadToast();
    } else {
      uni.hideLoading();
      uni.stopPullDownRefresh();
    }
    onLoadStatus();
    // // 组件数据加载状态
    // $emit("loadStatus", n);
  },
  {
    immediate: true,
  }
);

defineExpose({
  loadDatas,
});
</script>

<style scoped>
/* ::v-deep .u-loadmore__content__text {
		line-height: unset !important;
	} */
</style>
